// POC for GetSatisfaction:

// $Creator$
// $Originator: paul_m_thompson@yahoo.com $
// $Date: 2013-12-09 23:29:37 -0700 (Mon, 09 Dec 2013) $
// $DateTime$
// $File$
// $Script: GetSatPOC.ReorderMultiGrp $
// $Requires$
// $Provides$
// $Change$
// $Revision: 178 $
// $ActivationURL$
// Box Share URL: https://app.box.com/s/luqpjyj0e183uom4btg4

//    http://communities.serena.com/serena/topics/sort_list_in_multi_group_field

// This JavaScript will reorder entries in a MultiGroup field on a custom
//    Transition form.  The same code will *probably* work with other types
//    of Multi-X fields (not tested).  The caveat is that the field can't
//    use the "Allow Searching" style.

// Table properties for the field to be re-ordered:
//    Options / Style / List Box
//    Options / Search and Query / Show Full List

// To use:
//    1. Create a Process App JavaScript and import this file to it.
//       The Name can be anything.  Remember name for step 3 below.
//    2. Create a custom Transition form for your Process App.
//    3. In the form's JavaScripts tab, add the JavaScript created in step 1.
//    4. Edit the last line to use the name of your MultiGroup field.  You can
//       specify the field's Database name (less the TS_), the Display name,
//       or the UUID.
//    5. In the "ReorderMultiGroup", select the sorting option used by the
//       opts.sort() function call, or create your own comparison



function ReorderMultiGroup(str_FldName) {
   // LookupFieldId can find field TS_ID from Name, DB Name (less TS_) or UUID.
   // opts stores the OPTION value attrs and the text (displayed) values.
   // jq_Opts is jQuery object containing the OPTION elements.
   var   fldId = LookupFieldId(str_FldName) ,
         opts = [] , 
         jq_Opts = jQuerySBM('#' + fldId + ' option:not(#spaceroption)') ;

   // Get the values of the OPTION elements for the specified field.
   // Ignore the last OPTION which is a bunch of WHITESPACE.
   jq_Opts.each(function() {
      // console.log (this.value + " :: " + this.text) ;
      opts.push({key:this.value , val:this.text}) ;
   });

   // Sort the 'opts' array
   // 3 different sorting options here .... pick one.
   opts.sort( function(a,b) {
      // Return -1 if A < B
      // Return 0  if A == B
      // Return  1 if A > B

      // Sort by OPTION value attribute (numeric values)
      // return a[key] < b[key] ? -1 : ( a[key] > b[key] ? 1 : 0);

      // Sort by OPTION text using locale-sensitive comparison.
      // return a.val.localeCompare(b.val) ;

      // Sort in reverse order by OPTION text using locale-sensitive comparison.
      return b.val.localeCompare(a.val) ;
   });

   // Write it back to the OPTION elements.
   for (var i=0 ; i<opts.length ; i++) {
      jq_Opts[i].value = opts[i].key ;
      jq_Opts[i].text = opts[i].val ;
   }
}

// *** The param is the name of the MultiGroup field.
AddLoadCallback ( ReorderMultiGroup('MULTGRP_SORT_GRPS_POC_TST') ) ;
